import {Component} from 'react';
import React from 'react';
import {connect} from 'umi';
import HighPerformTable from '@/components/HighPerformTable';
import APIS from '@/apis';
import {PlusOutlined} from '@ant-design/icons';
import {Button, DatePicker, Form, Input, message, Select, Space} from 'antd';
import FilterByCourse from "@/components/FilterByCourse";
import Modal from "antd/lib/modal/Modal";
import {FormInstance} from "antd/es/form";
import moment from "moment";

/*实训管理页面*/
class TrainingManager extends Component<any, any> {
  actionRef: any;
  state = {
    allCourse: [],
    filter: 0,
    modalVisible: false,
    addTrain: false,
    startTime: "",
    endTime: "",
    courseId: 0,
    trainId: 0
  }

  constructor(props: any) {
    super(props);
  }

  form: FormInstance | undefined;

  componentDidMount() {
    APIS.CourseAPI.GetCourseList({
      current: 1,
      pageSize: 99999,
      state: -1
    }).then(res => this.setState({allCourse: res.data}))
  }

  requestGetData(
    params: {
      pageSize?: number;
      current?: number;
    },
    sorter: {
      [key: string]: 'ascend' | 'descend';
    },
    filter: {
      [key: string]: React.ReactText[];
    },
  ) {
    return APIS.ExamAPI.GetTrainingList({...params, sorter, filter, id: this.state.filter});
  }

  onCourseSelectChange(e: any, info: any) {
    const id = parseInt(info.key);
    this.setState({courseId: id});
  }

  clomns: any = [
    {
      title: '实训名称',
      dataIndex: 'title',
    },
    {
      title: '实训描述',
      dataIndex: 'description',
      valueType: 'textarea',
    },
    {
      title: '所属课程',
      dataIndex: 'courseId',
      render: (record: any) => (
        this.state.allCourse.map((v: any) => (
          v.id === record ? v.courseName : null
        ))
      )
    },
    {
      title: '考核点',
      dataIndex: 'checkPointer',
      render: (e: any, record: any) => (
        <a onClick={() => {
          this.props.history.push({
            pathname: '/teaching/exam/checkPointer',
            search: 'id=' + record.id,
          })
        }}>考核点</a>
      )
    },
    {
      title: '考核方式',
      dataIndex: 'checkMode',
      render: (record: any) => (
        record === 0 ? '视频' : '作品'
      )
    }
  ];

  render() {
    const {RangePicker} = DatePicker
    const {
      allCourse, modalVisible, addTrain, startTime, endTime, courseId, trainId
    } = this.state;
    return (
      <div>
        <FilterByCourse
          course={allCourse}
          getValue={(value) => {
            this.setState({filter: value});
            this.actionRef?.reload();
          }}/>
        <HighPerformTable<any>
          columns={this.clomns}
          requestGetData={this.requestGetData.bind(this)}
          ref={(ref) => (this.actionRef = ref)}
          handleChangeState={(data, state) => {
            return APIS.ExamAPI.ChangeTrainingState({id: data.id, state: state === true ? 1 : 0})
          }}
          handleDelete={(record: any) => {
            return APIS.ExamAPI.DeleteTraining({id: record.id})
          }}
          onClickUpdate={record => {
            this.setState({
              modalVisible: true,
              addTrain: false,
              startTime: record.startTime,
              endTime: record.endTime,
              courseId: record.courseId,
              trainId: record.id
            });
            setTimeout(() => {
              this.form?.setFieldsValue({
                "title": record.title,
                "description": record.description,
                "checkMode": record.checkMode
              })
            }, 300)
          }}
          toolBarRender={() => [
            <Button type="primary" key={"click"} onClick={() => {
              this.setState({modalVisible: true, addTrain: true, startTime: ""});
            }}>
              <PlusOutlined/> 新增实训
            </Button>,
          ]}
        />
        <Modal
          title={addTrain ? "新建实训" : "编辑实训"}
          visible={modalVisible}
          destroyOnClose={true}
          maskClosable={false}
          bodyStyle={{height: 400}}
          onCancel={() => this.setState({modalVisible: false})}
          footer={null}
        >
          <Form
            ref={(ref: any) => {
              this.form = ref
            }}
            onFinish={(value) => {
              if (addTrain) {
                if (startTime !== "" && endTime !== "") {
                  APIS.ExamAPI.CreateNewTraining({
                    title: value.title,
                    courseId: courseId,
                    checkMode: value.checkMode,
                    description: value.description,
                    startTime: startTime,
                    endTime: endTime,
                    state: 1
                  }).then((resp) => {
                    if (resp.code === 10000) {
                      this.setState({modalVisible: false})
                      this.actionRef?.reload();
                    }
                  }).catch(e => console.error(e))
                } else {
                  message.error("请选择起止时间")
                }
              } else {
                if (startTime !== "" && endTime !== "") {
                  APIS.ExamAPI.UpdateTraining({
                    title: value.title,
                    id: trainId,
                    courseId: courseId,
                    checkMode: value.checkMode,
                    description: value.description,
                    startTime: startTime,
                    endTime: endTime
                  }).then((resp) => {
                    if (resp.code === 10000) {
                      this.setState({modalVisible: false})
                      this.actionRef?.reload();
                    }
                  }).catch(e => console.error(e))
                } else {
                  message.error("请选择起止时间")
                }
              }
            }}
            onFinishFailed={(e) => console.error(e)}
          >
            <Form.Item label={"实训名称"} name={"title"} rules={[{required: true, message: '请输入实训名称'}]}>
              <Input/>
            </Form.Item>
            <Form.Item label={"实训描述"} name={"description"} rules={[{required: true, message: '请输入实训描述'}]}>
              <Input/>
            </Form.Item>
            {
              addTrain ?
                <Form.Item label={"所属课程"} name={"courseId"} rules={[{required: true, message: '请选择所属课程'}]}>
                  <Select defaultValue={""} onChange={this.onCourseSelectChange.bind(this)}
                          showSearch={true}
                  >
                    {allCourse.map?.((v: any, i) => (
                      <Select.Option key={v.id} value={v.courseName}>{v.courseName}</Select.Option>
                    ))}
                  </Select>
                </Form.Item>
                : null
            }
            <Form.Item label={"考核方式"} name={"checkMode"} rules={[{required: true, message: '请选择考核方式'}]}>
              <Select>
                <Select.Option key={0} value={0}>视屏</Select.Option>
                <Select.Option key={1} value={1}>作业</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item
              label='起止时间'
              name='time'
              rules={[{required: true, message: '请选择起止时间'}]}
            >
              <RangePicker
                defaultValue={startTime === "" || endTime === "" ? null : [moment(startTime), moment(endTime)]}
                onChange={(date, dateString) => {
                  console.log(dateString);
                  this.setState({
                    startTime: dateString[0],
                    endTime: dateString[1]
                  });
                }}
                showTime
              />
            </Form.Item>
            <Form.Item style={{float: 'right'}}>
              <Space>
                <Button onClick={() => this.setState({modalVisible: false})}>取消</Button>
                <Button type='primary' htmlType='submit'>确定</Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}

export default connect()(TrainingManager);
